<?php
header('Content-Type: application/json');
Header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE');
header("Access-Control-Allow-Headers: Content-Type");
header('Access-Control-Allow-Origin:*');   //跨域

require './mysql_init.php';

//创建地址图片名称
function createName(){
    $characters='abcdefghijklmnopqrstuvwxyz';
    $randomString=str_shuffle(str_repeat($characters,10));
    $randomName = substr($randomString, 0, 12); // 取前12个字符
    return $randomName.time();
}
//判断请求参数的长度
function judge_lenth($judge_len){
    foreach($judge_len as $i=>$n){
        if($i==0){
            if(strlen($n) <=0){
                return 3;
            }elseif(strlen($n) >=100){
                return 4;
            }
            
        }elseif($i==1 || $i==2){
            if(strlen($n) >8 || strlen($n) <=0){
                return 1;
            }elseif($n<0){
                return 2;
            }
        }elseif($i>=3){
            if(strlen($n) <=0){
                return 5;
            }elseif(strlen($n) >=800){
                return 6;
            }
        }
    }
    return 0;
}
//判断图片是否为空
function judge_null($judge_null){
    foreach($judge_null as $n){
        if(empty($n)){
            return 7;
        }
    }
    return 0;
}
//判断上传的文件的类型是否异常
function judge_file_suffix($judge_file_suffix,$allow_file_suffix){
    foreach($judge_file_suffix as $i){
        if(!in_array($i,$allow_file_suffix) || empty($i)){
            return 0;
        }
    }
    return 1;
}
//获取邮箱
function get_email($pdo,$session_id){
    try {
        // 准备查询语句
        $query = "SELECT email FROM session WHERE session_id = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $session_id);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['email'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//获取uid
function get_uid($pdo,$email){
    try {
        // 准备查询语句
        $query = "SELECT uid FROM users WHERE email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['uid'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//判断是否是商家
function is_seller($pdo,$uid){
    try {
        // 准备查询语句
        $query = "SELECT is_seller FROM users WHERE uid = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $uid);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['is_seller'];      //把查询结构赋值给$count
        if($result==1){
            return true;
        }else{
            return false;
        }
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//获取商家id
function get_sellerid($pdo,$uid){
    try {
        // 准备查询语句
        $query = "SELECT seller_id FROM sellers WHERE user_uid = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $uid);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['seller_id'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}

//插入商品信息
function insert_goods($pdo,$arr){
    try {
        // 准备插入语句并绑定参数
        $query = "INSERT INTO goods(seller_id, name, price, bewrite, cover_img_path, content_img1_path,  count, content_img2_path, content_img3_path) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);";
        $statement = $pdo->prepare($query);
        // 执行插入操作
        $statement->execute($arr);
        return 1;
        // echo "Data inserted successfully.";
    } catch (PDOException $e) {
        // echo "Error inserting data: " . $e->getMessage();
        return 0;
    }
}


if($_SERVER['REQUEST_METHOD'] === 'POST'){
    
    $response = [
        'status' => 0,
        'message' => '初始化'
    ];
    $uploadDir = './uploads/';
    $json_post=json_decode($_POST['goods'],true);

    $goods_name=$json_post['goods_name'];
    $goods_price=$json_post['goods_prace'];
    $goods_count=$json_post['goods_count'];
    $goods_bewrite=$json_post['goods_bewrite'];
    $session_id=$json_post['session_id'];

    $img_fengmian=$_FILES['image_fengmian']['name'];
    $img1=$_FILES['image1']['name'];
    $img2=$_FILES['image2']['name'];
    $img3=$_FILES['image3']['name'];

    $judge_file_suffix=[pathinfo($img_fengmian,PATHINFO_EXTENSION),pathinfo($img1,PATHINFO_EXTENSION),pathinfo($img2,PATHINFO_EXTENSION),pathinfo($img3,PATHINFO_EXTENSION)];
    $allow_file_suffix=['jpg','JPG','png','PNG','jpeg','JPEG'];

    $judge_len=[$goods_name,$goods_price,$goods_count,$goods_bewrite];    
    $judge_null=[$img_fengmian,$img1,$img2,$img3];


    if(judge_lenth($judge_len)==0 && judge_null($judge_null)==0 && judge_file_suffix($judge_file_suffix,$allow_file_suffix)==1){
        $img_fengmian=$uploadDir.createName().rand().'.'.$judge_file_suffix[0];
        $img1=$uploadDir.createName().rand().'.'.$judge_file_suffix[1];
        $img2=$uploadDir.createName().rand().'.'.$judge_file_suffix[2];
        $img3=$uploadDir.createName().rand().'.'.$judge_file_suffix[3];
        move_uploaded_file($_FILES['image_fengmian']['tmp_name'], $img_fengmian);
        move_uploaded_file($_FILES['image1']['tmp_name'], $img1);
        move_uploaded_file($_FILES['image2']['tmp_name'], $img2);
        move_uploaded_file($_FILES['image3']['tmp_name'], $img3);

        $email=get_email($pdo,$session_id);
        $uid=get_uid($pdo,$email);
        if(is_seller($pdo,$uid)){
            $seller_id=get_sellerid($pdo,$uid);
            $arr=[$seller_id,$goods_name,(float)$goods_price,$goods_bewrite,$img_fengmian,$img1,(int)$goods_count,$img2,$img3];
            $fd=insert_goods($pdo,$arr);
            $response = [
                'status' => 1,
                'message'=>'上传成功'
            ];
        }else{
            $response = [
                'status'=> 0,
                'message'=>'不是商家'
            ];
        }
    }else{
        $response = [
            'status'=>0,
            'message'=>'上传的参数有误'
        ];
    }
        
    
    // 将响应数据以 JSON 格式返回给前端
    echo json_encode($response);
}else{
    // 返回上传失败的信息
    $response = [
        'status' => 0,
        'message' => '不是post请求'
    ];
    echo json_encode($response);

}


?>